//
//  ViewController.swift
//  8-4 正则表示
//
//  Created by cyc on 16/3/10.
//  Copyright © 2016年 cyc. All rights reserved.
//

import UIKit
//8-4 正则匹配
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
         let source = "<a href=\"http://app.weibo.com/t/feed/5yiHuw\" rel=\"nofollow\">我的@女包iPhone 6 Plus</a><a href=\"http://app.weibo.com/t/feed/5yiHuw\" rel=\"nofollow\">我的@女包iPhone 6 Plus</a>"
    print("sinSource:\(source.sinSource())")
       //test01()
    
    }
    //方法
    //  "source": "<a href=\"http://app.weibo.com/t/feed/5yiHuw\" rel=\"nofollow\">iPhone 6 Plus</a>",
    private func  test01(){
        let source = "<a href=\"http://app.weibo.com/t/feed/5yiHuw\" rel=\"nofollow\">我的@女包iPhone 6 Plus</a><a href=\"http://app.weibo.com/t/feed/5yiHuw\" rel=\"nofollow\">我的@女包iPhone 6 Plus</a>"
    /*
      pattern:匹配原则
         1.: 匹配任何字符串，不包括换行
         2* : 匹配任意多数量的字符
         3 ?: 尽可能少的匹配
        4.(): 捕获（）里面内容也做为匹配结果返回
    */
        let pattern=">(.*?)<"
       // let pattern=">.*<"
        //options: NSRegularExpressionOptions.DotMatchesLineSeparators可以匹配换行
         let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        //String: 从哪内容里面来查找
        //<#T##NSRange#> ： 要查找的字符串的范围
        // 返回结果：NSTextCheckingResult
        //查找command+shift+o
        //public var numberOfRanges: Int { get }:匹配到的范围数量
//        @available(iOS 4.0, *)
//        public func rangeAtIndex(idx: Int) -> NSRange根据idx获取匹配范围
//        @available(iOS 5.0, *)
//        public func resultByAdjustingRangesWithOffset(offset: Int) -> NSTextCheckingResult
//
   let result = regular.firstMatchInString(source, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: source.characters.count))
        //匹配范围的数量
        let count = result?.numberOfRanges ?? 0
//        for i in 0..<count {
//            let range = result?.rangeAtIndex(i)
//            // 匹配字符串
//             let  subString = (source as NSString).substringWithRange(range!)
//            print("range:\(range)")
//            print("subString :\(subString )")
            //range:Optional((59,15))
            //subString :>iPhone 6 Plus<
            //range:Optional((59,20))
           // subString :>我的@女包iPhone 6 Plus<
            //subString :我的@女包iPhone 6 Plus
       //}
        
        if count>1{
            //获取index=1的范围来截取0 1
            let range = result?.rangeAtIndex(1)
            //            // 匹配字符串
            let  subString = (source as NSString).substringWithRange(range!)
            print("range:\(range)")
            print("subString :\(subString )")
        }
    }
   }

